//
//  KDBaseBoardTool.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/6/9.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "KDBaseBoardTool.h"
#import "FMDB.h"
#import "KDBaseBoardModel.h"
@implementation KDBaseBoardTool
static FMDatabase *_db;
+ (void)initialize
{
    //1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"KDBaseBoard.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    //2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_baseboard (id integer PRIMARY KEY AUTOINCREMENT, baseBoardModel blob NOT NULL,idstr text NOT NULL UNIQUE);"];
}
//根据请求参数读取相应的侧边栏model数据
+ (KDBaseBoardModel *)baseBoardMoldeWithParams:(NSDictionary *)params
{
    //根据请求参数生成对应的查询SQL语句
    NSString *sql = [NSString stringWithFormat:@"SELECT *FROM t_baseboard WHERE idstr = %@", params[@"idstr"]];
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *baseBoards = [NSMutableArray array];
    while (set.next) {
        //NSData ————》NSDictionary
        NSData *data = [set objectForColumnName:@"baseBoardModel"];
        KDBaseBoardModel *baseBoard = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [baseBoards addObject:baseBoard];
    }
    if (baseBoards.count == 0) {//
        return nil;
    }
    KDBaseBoardModel *model = baseBoards[0];
    return model;
}
+ (void)saveBaseBoardModel:(KDBaseBoardModel *)model
{
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        [_db executeUpdateWithFormat:@"replace into t_baseboard (baseBoardModel, idstr) VALUES (%@, %@);", data,model.idstr];
}
@end
